class sheet{
    //构造函数
    constructor(args) {
        this.api = args.api;
        this.postData = args.postData||{};
        this.buttons = args.buttons||[];
        this.storage = {};
    }
    //新建
    create(){
        if(!this.storage.naive)
            return;
        window.location.href = `../../views/create.html?naive=${this.storage.naive}`;
    }
    //排序
    order(order){
        this.postData = Object.assign(this.postData,{order});
    };
    //删除
    deleteModel(len){
        if(!this.storage.naive)return;
        let primaryKey = this.storage.editor.primaryKey;
        let yes = window.confirm(`是否确认删除此条数据${primaryKey}:${this.storage.currentData[len][primaryKey]}`);
        if(!yes)return;
        getAgent(this.storage.naive).invoke("delete",{id:this.storage.currentData[len][primaryKey]})
    };
    //获得表格数据
    async getSheet(){
        return ServerAgent.invoke(this.api,this.postData).then(res=>{
            console.log(res);
            this.storage.currentData = res.args.data;
            this.storage.naive = res.args.naive;
            this.storage.currentPage = res.args.page;
            this.storage.allPage = res.args.allPage;
            this.storage.editor = res.args.editor;
            this.storage.count = res.args.count;
            let table = "<table border='1' style='margin: 10px auto 0;width:1200px;text-align: center; cellpadding:0; cellspacing:0;table-layout:fixed;'><thead><tr></tr></thead><tbody></tbody></table>";
            $(".sectionMainTable").children().remove();
            $(".sectionMainTable").append(table);
            if(this.storage.currentData.length === 0)return;
            for(let i in this.storage.currentData){
                let tr = "<tr></tr>";
                $("table tbody").append(tr);
            }
            return this;
        });
    };
    //初始化表格
    async init(index){
        if(isNaN(index))index = 0;
        if (index >= this.storage.allPage)index = this.storage.allPage-1;
        if(index<0)index = 0;
        this.postData = Object.assign(this.postData,{page:index});
        return this.getSheet().then(res=>{
            this.setButton();this.setTable();this.setPageButtons();
            return res;
        });
    }
    //分页按钮设置
    setPageButtons(){
        let allPage = this.storage.allPage;
        window.sessionStorage.setItem("page",this.storage.currentPage);
        let currentPage = Number(this.storage.currentPage);
        let start = currentPage-5<0?0:(allPage<currentPage+5?allPage > 10?allPage-10:0:currentPage-5);
        let end = currentPage+5>allPage?allPage:currentPage+5<10?(allPage<10?allPage:10):(currentPage+5<allPage?currentPage+5:allPage);
        let pageNum=`<li onclick="model.init(${currentPage-1})"><a href="javascript:void(0);">«</a></li>`;
        for(let i = start ; i < end ; i++){
            if (i === currentPage){
                pageNum+=`<li onclick="model.init(${i})"><a style="width:20px;background:#ff0000" href="javascript:void(0);">${i+1}</a></li>`;
            }else {
                pageNum+=`<li onclick="model.init(${i})"><a style="width:20px" href="javascript:void(0);">${i+1}</a></li>`;
            }
        }
        pageNum+=`<li onclick="model.init(${currentPage+1})"><a href="javascript:void(0);">»</a></li>`;
        $(".pagination").eq(0).html(pageNum);
    };
    //渲染表格
    setTable(){
        let tHead = "";
        let editor = this.storage.editor;
        let list = this.storage.currentData;
        for (let i in editor.title) {
            tHead += `<th style="width:150px;height:30px;background:#ccc;">${editor.title[i]}</th>`;
        }
        if (tHead !== "") $("table thead tr").append(tHead);
        for(let i in list){
            let tBody = "";
            for(let key in editor.title){
                if(list[i][key]===undefined){
                    continue;
                }
                if(editor.list.indexOf(key) >= 0){
                    tBody += `<td onmouseover="$(this).css('background','#fffa20')" onmouseleave="$(this).css('background','#fffcf3')" ondblclick="model.showElement(this,'${i}','${key}')" style="background:#fffcf3;width:150px;height:30px;word-wrap:break-word;">${typeof list[i][key] === 'object'?JSON.stringify(list[i][key]):list[i][key]}</td>`;
                }else {
                    tBody += `<td style="width:150px;height:30px;word-wrap:break-word;">${typeof list[i][key] === 'object'?JSON.stringify(list[i][key]):list[i][key]}</td>`;
                }
            }
            //
            // for(let key in list[i]){
            //     if(!editor.title[key]){
            //         continue;
            //     }
            //     if(editor.list.indexOf(key) >= 0){
            //         tBody += `<td onmouseover="$(this).css('background','#fffa20')" onmouseleave="$(this).css('background','#fffcf3')" ondblclick="model.showElement(this,'${i}','${key}')" style="background:#fffcf3;width:150px;height:30px;word-wrap:break-word;">${typeof list[i][key] === 'object'?JSON.stringify(list[i][key]):list[i][key]}</td>`;
            //     }else {
            //         tBody += `<td style="width:150px;height:30px;word-wrap:break-word;">${typeof list[i][key] === 'object'?JSON.stringify(list[i][key]):list[i][key]}</td>`;
            //     }
            // }
            $("table tbody tr").eq(i).append(tBody);
        }
    };
    //增加自定义按钮
    setButton(){
        let list = this.storage.currentData;
        let buttons = this.buttons;
        let tHead = "";
        for(let i in buttons){
            tHead += `<th style="width:150px;height:30px;background:#ccc;">${buttons[i].title}</th>`;
            for(let j in list){
                let tBody = "";
                let token = "token_"+parseInt(Math.random()*10000000000);
                tBody += `<td onmouseover="$(this).css('background','#fffa20')" onmouseleave="$(this).css('background','#ffffff')" onclick="model.buttons[${i}].fn(${j});" style="width:150px;height:30px;">${buttons[i].text}</td>`;
                $("table tbody tr").eq(j).append(tBody);
            }
        }
        $("table thead tr").append(tHead);
    };
    //双击编辑
    showElement(element,len,key) {
        let editor = this.storage.editor;
        if(editor.list.indexOf(key) < 0)return;
        let oldhtml = element.innerHTML;
        //如果已经双击过，内容已经存在input，不做任何操作
        if(oldhtml.indexOf('type="text"') > 0){
            return;
        }
        //创建新的input元素
        let newobj = document.createElement('input');
        //为新增元素添加类型
        newobj.type = 'text';
        //为新增元素添加value值
        newobj.value = oldhtml;
        //为新增元素添加光标离开事件
        newobj.onblur = ()=> {
            element.innerHTML = newobj.value == oldhtml ? oldhtml : newobj.value;
            //当触发时判断新增元素值是否为空，为空则不修改，并返回原有值
            if(newobj.value != oldhtml){
                this.storage.currentData[len][key] = element.innerHTML;
                let data = {};
                data[key] = this.storage.currentData[len][key];
                if(editor) {
                    let primaryKey = editor.primaryKey;
                    if (primaryKey){
                        data[primaryKey] = this.storage.currentData[len][primaryKey];
                    }
                    if(this.storage.naive)
                        getAgent(this.storage.naive).invoke("editor",data);
                    console.log(data);
                }
            }
        };
        //设置该标签的子节点为空
        element.innerHTML = '';
        //添加该标签的子节点，input对象
        element.appendChild(newobj);
        //设置选择文本的内容或设置光标位置（两个参数：start,end；start为开始位置，end为结束位置；如果开始位置和结束位置相同则就是光标位置）
        newobj.setSelectionRange(0, oldhtml.length);
        //设置获得光标
        newobj.focus();
    }
    //获得当天全天的时间
    getEndTime(){
        let currentDate = new Date(new Date().getTime() + 24*60*60*1000);
        let MM = currentDate.getMonth()+1>9?currentDate.getMonth()+1:"0"+(currentDate.getMonth()+1);
        let dd = currentDate.getDate() > 9 ? currentDate.getDate():"0"+currentDate.getDate();
        return currentDate.getFullYear()+"-"+MM+"-"+dd;
    }
}
